function myBrowser(){
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera) {
        return "Opera"
    }; //判断是否Opera浏览器
    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    } //判断是否Firefox浏览器
    if (userAgent.indexOf("Chrome") > -1){
    	return "Chrome";
	}
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    } //判断是否Safari浏览器
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        return "IE";
    }; //判断是否IE浏览器
}

/**
 * 附件下载
 * @param attachId 附件id
 */
function attachDowmload(attachId){
	$.ajax({
		type : "POST",
		url : ctx+"/attach/download.do",
		data: {attachId:attachId},
		dataType : "json",
		success : function(data) {
			if(data.url){
				var mb = myBrowser();
				if('IE' == mb){
					window.location.href = data.url;
				}else{
					window.open(data.url,"_blank");
				}
			}else{
				alert("获取不到当前附件下载");
			}
		}
	});
}


function window_action(url){
	if(!checkStrIsBlank(url)){
		window.open(url,"_blank");
	}
}

function dsft_action(url){
	if(!checkStrIsBlank(url)){
		window.open(url,"_blank");
	}
}

/**
 * 输入限制，只能输入数字
 * function onkeyup()
 * function onafterpaste()
 */
function onKeyUp(obj){
	if(obj.value.length==1){
		obj.value=obj.value.replace(/[^1-9]/g,'')
	}else{
		obj.value=obj.value.replace(/\D/g,'')
	}
	
}

function onAfterPaste(obj){
	if(obj.value.length==1){
		obj.value=obj.value.replace(/[^1-9]/g,'')
	}else{
		obj.value=obj.value.replace(/\D/g,'')
	}
	
}

/**
检查输入的字符是否具有特殊字符
输入:str  字符串
返回:true 或 flase; true表示包含特殊字符
*/
function checkQuote(str) {
    var items = new Array("~", "`", "!", "@", "#", "$", "%", "^", "&", "{", "}", "[", "]", "(", ")");
    items.push(":", ";", "'", "|", "\\", "<", ">", "?", "/", "<<", ">>", "||" ,"\"");
    items.push("+", "_" ,"*");
    str = str + "";
    for (var i = 0; i < items.length; i++) {
        if (str.indexOf(items[i]) >= 0) {
            return true;
        }
    }
    return false;
}


/**
 * 在线申办跳转
 * @param url 在线申办地址
 */
function zxsb_action(url){
	window.open(url,"_blank");
}

/**
 * 搜索选项切换
 * @param obj
 */
function ssfw(obj){
	$(".sel-on").removeClass("sel-on gradient-light-blue").removeAttr("aria-pressed");
	$(obj).addClass("sel-on gradient-light-blue").attr("aria-pressed","true");
}

function checkXzqhJb(xzqh){
	var xzqhArr = xzqh.split('');
	var tanslatorStr = '';
	for(var i = 0;i<xzqhArr.length-1;i++){
		if(xzqhArr[i] == '0'){
			if(compareFooter(xzqhArr,i)){
				tanslatorStr = xzqh.substring(0, i);
				break;
			}else{
				continue;
			}
		}
	}
	if(tanslatorStr==''){
		return xzqh;
	}
	return tanslatorStr ;
}

function compareFooter(xzqhArr,i){
	for (var j = i; j < xzqhArr.length; j++) {
		if(xzqhArr[j] != '0'){
			return false;
		}
	}
	return true;
}

function checkStrIsBlank(str){
	if(0 === str) return false;
	if(str){
		if(str != 'null' && str != '' && typeof(str) != undefined){
			return false;
		}
	}
	return true;
}
/**
 * 字符串处理：为空返回空字符串，否则返回字符串本身
 * @param str 待处理字符串
 * @param returnStr 为空时返回的字符串，为空默认返回空字符串
 * @returns 
 */
function handleStr(str, returnStr) {
	if (checkStrIsBlank(str)) {
		if (checkStrIsBlank(returnStr)) {
			return '';
		} else {
			return returnStr;
		}
	} else {
		return str;
	}
}

/**
 * 格式化日期
 * @param fmt 格式，如yyyy-MM-dd
 */
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
/**
 * 根据key值获取url参数
 * @param key
 * @param win 窗口对象
 */
function getQueryString(key, win) {
	var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
	var r = win.location.search.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	}
	return null;
}
/**
 * 改变头部tab签hover态
 * @param index tab索引（整型数字），起始值0
 */
function changeHeaderNavHover(index) {
	if (!checkStrIsBlank(index)) {
		$(".navigation li").removeClass("active");
		$($(".navigation li")[index]).addClass("active");
	}
}

//去掉字符串中所有空格(包括中间空格,需要设置第2个参数为:g) 
function trim(str,is_global){
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g,"");
    if(is_global.toLowerCase()=="g"){
        result = result.replace(/\s/g,"");
     }
    return result;
}
/**
 * 空列表提示信息html生成
 * @param content 空列表提示内容
 * @returns 空列表提示信息
 */
function emptyListHtml(content) {
	if (!content) {
		content = '当前条件下没有相关信息';
	}
	var html = '<div class="placeholder placeholder-empty"><div class="placeholder-bd">';
	html += '<div class="placeholder-bd"><div class="placeholder-icon"></div>';
	html += '<div class="placeholder-title">'+content+'</div></div></div></div>';
	return html;
}
/**
 * 提示加载中html生成
 * @param content
 * @returns {String}
 */
function loadingHtml(content) {
	if (!content) {
		content = '正在加载';
	}
	var html = '<div class="placeholder placeholder-loading"><div class="placeholder-bd">';
	html += '<div class="placeholder-icon">';
	html += '</div><div class="placeholder-title">'+content+'</div></div></div>';
	return html;
}
/**
 * 用户登录
 * @returns
 */
function login(){
	//方法定义在getLoginInfo.js里
	gotoLogin();
}
/**
 * 退出登录
 * @returns
 */
function logout(){
	confirm({msg:"确定要退出登录吗？", btnOkClick:function(){
		//方法定义在getLoginInfo.js里
		gotoLogout();
	}});
}

function getLocationAdvice(callback){
	$.ajax({
		type : "GET",
		url : ctx+"/api/ip/location",
		//timeout : 5000,
		dataType: 'json',
		success: function(data){
			if(data.statusCode != "200" || !data.data || data.data.status !=0 ){
				console && console.log("ip定位失败")
				callback({
					areaName: '广东省',
					areaCode: '440000'
				})
				return;
			}
			data = data.data
			var areaCode = data.result.ad_info.adcode.toString()
			var areaName = data.result.ad_info.city
			if(areaCode.indexOf('44') != 0){
				areaCode = '440000'
				areaName = '广东省'
			}
			if(areaCode == '440000'){
				areaName = '广东省'
			}
			callback({
				areaName: areaName,
				areaCode: areaCode
			})
		},
		error: function(){
				callback({
					areaName: '广东省',
					areaCode: '440000'
				})
			},
		complete:function(XMLHttpRequest,status){ 
		　　　　if(status=='timeout'){
				console && console.log('定位超时!')
		　　　　}
		}
	})
}

//ip location
function getIpLocation(callback){
	var location = sessionStorage && sessionStorage.getItem('ip.location')
	if(location){
		callback(JSON.parse(location))
		return
	}
	getLocationAdvice(function(data){
		sessionStorage && sessionStorage.setItem('ip.location',JSON.stringify(data))
		callback(data)
	})
}
/**
 * 分页控件返回数据时创建默认对象
 */
function createDefaultObject() {
	var obj = new Object();
	obj.page = 1;
	obj.pageSize = 10;
	obj.totalCount = 0;
	obj.result = '';
	return obj;
}
/**
 * 个性化接口返回数据为空或不符合要求处理
 */
function handleErrorCustomConfig() {
	
}
/**
 * 关闭窗口
 */
function closeWindow() {
	window.close();
	window.history.go(-1);
}

/**
 * 单点跳转
 * @param url	跳转链接
 */
function sso(url){
	var ssoUrl = getSSOUrl(url)
	var win = window.open(ssoUrl,"_blank");
	win.opener=null;
}

function getSSOUrl(url){
	if(!url) {
		return;
	}
	if(!gdbsTokenId){
		gdbsTokenId = '';
	}
	if(url.indexOf("?") > 0) {
		url += "&gdbsTokenId=" + gdbsTokenId;
	} else {
		url += "?gdbsTokenId=" + gdbsTokenId;
	}
	return url
}

$(document).ready(function(){
$("#navigationHall").HallNav({
	url : ctx+"/custom-config/gdbsNav/current",
    asyncLoad : true,
    homePage:ctx+'/index',
    context:ctx,
    xzqhdm:region,
    //关闭服务端页面模式
    serverSidePage : false,
  	//数据自定义填充
    render : function(data){
    	if(data){
    		
    		var current = data.data.currentArr;
        	var header_title = '广东省';
        	if(system_type == 'product'){
        		var sites_url = '//www.gdzwfw.gov.cn'
        	}else {
        		var sites_url = ctx+'/index';
        	}
        	
        	
        	if(current && current.length>0 && current[current.length-1].ORGAREACODE!='440000'){
        		var headerTitle = '';
        		var headerUrl = '';
        		$.each(current,function(i,n){
        			if(n.ORGTYPE === '市分厅' && n.ORGAREACODE!='440000'){
        				headerTitle += n.ORGSNAME;
        				headerUrl = '?region=' + n.ORGAREACODE;
        			}else if(n.ORGTYPE === '区县分厅'){
        				headerTitle += n.ORGSNAME;
        				headerUrl = '?region=' + n.ORGAREACODE;
        			}
        		});
        		header_title = headerTitle;
        		sites_url += headerUrl;
        		
        		var orgname = current[current.length-1].ORGNAME;
        		var orgareacode = current[current.length-1].ORGAREACODE;        		
        		// 同时写入部门窗口banner区和隐藏标签名称框
        		var bannerTitleObj = $(".banner-hall-title");
        		if(bannerTitleObj && checkStrIsBlank($(bannerTitleObj).html())) {
        			$(bannerTitleObj).html(orgname);
        		}
        		var inputTitleObj = $("#input-title");
        		if (inputTitleObj && checkStrIsBlank($(inputTitleObj).val())) {
        			document.title = orgname + "窗口";
        		}      			       		
        	}
        	
        	if(!checkStrIsBlank(getQueryString("orgCode",window))){ //如果是orgCode，则需要通过orgCode解析出region
        		getCustomConfig('gdbsPortal/common',{region:orgareacode},commonRender);
        	}
        	$("#headerTitle").html('<a href="'+sites_url+'">'+header_title+'</a>');
    	}
    },
    //自定义传递到服务端的参数
    params : function(){
    	var params = {};
    	if(orgCode){
    		params.orgCode = orgCode;
    	}
        return params;
    }
});
})